package com.jl.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.commons.utils.CopyBean;
import com.jl.model.Component;
import com.jl.model.DamageComponent;
import com.jl.service.IComponentService;
import com.jl.service.IDamageComponentService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 零件表 前端控制器
 * </p>
 *
 * @author JiangJian
 * @since 2019-03-06
 */
@Controller
@RequestMapping("/component")
public class ComponentController extends BaseController {

    @Autowired
    private IComponentService componentService;

    @GetMapping("/componentDataGrid")
    @RequiresPermissions("/component/componentDataGrid")
    public String componentList(){
        return "component_list";
    }


    @GetMapping("/add")
    @RequiresPermissions("/component/add")
    public String addComponentPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "component_add";
    }

    /**
     * 一定是add
     * @param json
     * @return
     */
    @PostMapping("/add")
    @RequiresPermissions("/component/add")
    @ResponseBody
    public ResultData addComponent(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Component component = JSON.parseObject(value,Component.class);
        //表示是新增
        if(componentService.isComponentNumberUsed(component.getNumber())){
            //被占用
            return fail(ErrorCode.COMPONENT_NUMBER_USED,ErrorMessage.COMPONENT_NUMBER_USED);
        }
        component.setCreateId(getUserId());
        component.setGmtCreate(new Date());

        componentService.save(component);
        return success(component);
    }


    @GetMapping("/edit")
    @RequiresPermissions("/component/edit")
    public String editComponentPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "component_add";
    }

    /**
     * 一定是edit
     * @param json
     * @return
     */
    @PostMapping("/edit")
    @RequiresPermissions("/component/edit")
    @ResponseBody
    public ResultData editComponent(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Component component = JSON.parseObject(value,Component.class);
        //表示是修改
        boolean canUse = componentService.isComponentNumberCanUse(component.getNumber(),component.getId());
        if(!canUse){
            return fail(ErrorCode.COMPONENT_NUMBER_USED,ErrorMessage.COMPONENT_NUMBER_USED);
        }
        component.setModifyId(getUserId());
        component.setGmtModified(new Date());

        componentService.updateById(component);
        return success(component);
    }

    @PostMapping("/delete")
    @RequiresPermissions("/component/delete")
    @ResponseBody
    public ResultData deletesComponent(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        boolean b = componentService.deleteComponentByIds(ids);
        if(b){
            return success();
        }
        return fail();
    }

    /**
     * 一定是dataGrid
     * @param current
     * @param pageSize
     * @param searchCol
     * @param searchValue
     * @return
     */
    @PostMapping("/dataGrid")
    @RequiresPermissions("/component/dataGrid")
    @ResponseBody
    public ResultData componentDataGrid(Long current,Long pageSize,String searchCol,String searchValue,String json){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<Component> queryWrapper = new QueryWrapper<>();
        //目前的查询只有单表
        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(StringUtils.isNotBlank(jsonObject.getString("name"))){
                queryWrapper.like("t.name",jsonObject.getString("name"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("number"))){
                queryWrapper.like("t.number",jsonObject.getString("number"));
            }
            if(null!=jsonObject.getLong("type") && jsonObject.getLong("type")!=0){
                queryWrapper.eq("t.type",jsonObject.getString("type"));
            }
            if(null!=jsonObject.getInteger("avgLife") && jsonObject.getInteger("avgLife")!=0){
                queryWrapper.ge("t.avg_life",jsonObject.getString("avgLife"));
            }
            if(null!=jsonObject.getInteger("level") && jsonObject.getInteger("level")!=0){
                queryWrapper.eq("t.level",jsonObject.getString("level"));
            }
        }else{
            if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
                if(searchCol.equals(Constants.ID)){
                    queryWrapper.eq("t.id",searchValue);
                }else{
                    queryWrapper.like("t."+searchCol,searchValue);
                }
            }
        }

        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);

        componentService.selectComponentDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }

    @PostMapping("/dataGridByModelId")
    @RequiresPermissions("/component/dataGrid")
    @ResponseBody
    public ResultData componentDataGridByPartId(Long modelId){
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(Constants.FIRST_PAGE);
        pageDataInfo.setSize(Constants.MAX_PAGE_SIZE);
        componentService.selectComponentDataGridByModelId(pageDataInfo,modelId);
        return success(pageDataInfo);
    }
}
